/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import twaver.Element;
import twaver.Generator;
import twaver.TDataBox;
import twaver.TWaverUtil;
import twaver.VisibleFilter;
import twaver.swing.TExpandPane;
import twaver.swing.TableLayout;
import twaver.tree.TTree;
import demo.tree.TreePopupMenuGenerator;
import demo.tree.TreeToolBar;

public class MainPane extends JPanel{
	
    public static TDataBox box;
    private TTree tree;   
    private JSplitPane rootSplit = new JSplitPane();
    private JTextField txtSearch = new JTextField();
    private JEditorPane txtReadMe = new JEditorPane();
    private JScrollPane scrollReadMe = new JScrollPane(txtReadMe);  
    private NavigateManager navigateManager; 
    
    public MainPane() {   
    	box = new TDataBox("TWaver Demos");
    	tree = new TTree(box);
        DemoNodeFactory.createAll(box);  

        tree.setEnsureVisibleOnSelected(true);
        tree.setPopupMenuGenerator(new TreePopupMenuGenerator(tree));
    	tree.expandRow(0);
    	
    	tree.setElementLabelGenerator(new Generator(){
			public Object generate(Object element) {
				String name = ((Element)element).getName();
				if(element instanceof DemoNode){
					DemoNode node = (DemoNode)element;
					if(DemoNodeFactory.newMap.containsKey(node.getDemoClass())){
						return "<html><b>" + name + "<font color=red> NEW</font></b></html>";
					}
					if(DemoNodeFactory.updateMap.containsKey(node.getDemoClass())){
						return "<html><b>" + name + "<font color=blue> UPDATED</font></b></html>";
					}
				}
				return name;
			}
    	});

    	JLabel lbSearch = new JLabel();
        lbSearch.setText(" Quick Search:");
        JPanel searchPane = new JPanel(new BorderLayout());
        searchPane.add(lbSearch, BorderLayout.NORTH);     
        searchPane.add(DemoUtil.createDropDownSelector(this, txtSearch), BorderLayout.CENTER);        
        TExpandPane searchPopup = new TExpandPane(searchPane, TExpandPane.NORTH, true, false);
        
        MemoryChartPane memoryChartPane = new MemoryChartPane();
        TExpandPane memoryChartExpandPane = new TExpandPane(memoryChartPane, TExpandPane.SOUTH, true, false);       
        
    	double[] rows = new double[] {
        	TableLayout.PREFERRED,
        	TableLayout.PREFERRED,
        	TableLayout.FILL,
        	TableLayout.PREFERRED,
    	};

        double[] columns = new double[] {
        	TableLayout.FILL,
        };
        JPanel leftPanel = new JPanel(new TableLayout(columns, rows));
        leftPanel.add(searchPopup, "0,0");
        leftPanel.add(new TreeToolBar(tree), "0,1");
        leftPanel.add(new JScrollPane(tree), "0,2");
        leftPanel.add(memoryChartExpandPane, "0,3");
        
        rootSplit.setContinuousLayout(true);
        rootSplit.setOneTouchExpandable(true);
        rootSplit.setLeftComponent(leftPanel);
        rootSplit.setRightComponent(scrollReadMe);
        
        this.navigateManager = new NavigateManager(tree, rootSplit, scrollReadMe);
		rows = new double[] { 
			TableLayout.PREFERRED, 
			TableLayout.FILL,
		};
		columns = new double[] { 
			TableLayout.FILL,
			TableLayout.PREFERRED, 
			TableLayout.PREFERRED, 
			TableLayout.PREFERRED, 
			TableLayout.PREFERRED, 
		}; 

        this.setLayout(new TableLayout(columns, rows));
        this.add(DemoUtil.createMenuBar(this), "0,0");
        this.add(createExportImageButton(), "1,0");
        this.add(navigateManager.getBackButton(), "2,0");
        this.add(navigateManager.getForwardButton(), "3,0");
        this.add(navigateManager.getFullButton(), "4,0");
        this.add(rootSplit, "0,1,4,1");	

        try {        
        	txtReadMe.setEditable(false);
			txtReadMe.setPage(getClass().getResource("/demo/resource/README.html"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		txtSearch.addKeyListener(new KeyAdapter(){
			public void keyReleased(KeyEvent e) {
				if(e.getKeyChar() == KeyEvent.VK_ESCAPE){
					txtSearch.setText(null);
				}
				tree.updateTViewUI();
				tree.expandAll();
				selectNode();
			}
		});
        tree.addVisibleFilter(new VisibleFilter(){
			public boolean isVisible(Element element) {
		        String text = txtSearch.getText();
		        if (!(element instanceof DemoNode) || text == null || text.trim().equals("")) {
		            return true;
		        }
				return element.getName().toLowerCase().indexOf(text.toLowerCase()) >= 0;
			}
        });
        SwingUtilities.invokeLater(new Runnable(){
			public void run() {
				txtSearch.requestFocus();
			}
        });
    }
    
    public void clearSearch(){
    	txtSearch.setText("");
    	tree.updateTViewUI();
    	tree.expandAll();
    	Element element = tree.getDataBox().getLastSelectedElement();
    	if(element != null){
    		tree.ensureVisible(element);
    	}
    }
    
    public void selectNode() {
        String text = txtSearch.getText();
        if (text == null || text.trim().equals("")) {
            return;
        } else {
            text = text.trim().toLowerCase();
            List list = new ArrayList();
            Iterator it = box.iterator(DemoNode.class);
            while (it.hasNext()) {
                Element element = (Element) it.next();
            	if(tree.isVisible(element)){
            		list.add(element);
            	}
            }
            box.getSelectionModel().setSelection(list);
        }
    }
    
    private JButton createExportImageButton(){
		JButton button = new JButton(TWaverUtil.getIcon("/demo/resource/images/exportImage.png"));
		button.setFocusPainted(false);
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				TWaverUtil.exportImage(rootSplit.getRightComponent());
			}
		});
		return button;
    }
}